import mongoose from 'mongoose';
import Clothes from '../models/Clothes.js';
import Outfit from '../models/Outfit.js';

// 获取衣物列表（支持分页和筛选）
export const getClothesList = async (req, res) => {
  try {
    const { page = 1, pageSize = 12, type, color, season, occasion, favorite } = req.query;
    const userId = req.user._id;

    // 构建查询条件
    const query = { userId };

    if (type) {
      query.type = type;
    }

    if (color) {
      query.color = color;
    }

    if (season) {
      query.season = season;
    }

    if (occasion) {
      query.occasions = occasion;
    }

    if (favorite === 'true') {
      query.isFavorite = true;
    }

    // 分页计算
    const currentPage = parseInt(page);
    const size = parseInt(pageSize);
    const skip = (currentPage - 1) * size;

    // 查询数据
    const clothes = await Clothes.find(query)
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(size);

    const total = await Clothes.countDocuments(query);

    res.json({
      items: clothes,
      total,
      page: currentPage,
      pageSize: size
    });
  } catch (error) {
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
};

// 获取单个衣物详情
export const getClothesDetail = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user._id;

    const clothes = await Clothes.findOne({ _id: id, userId });

    if (!clothes) {
      return res.status(404).json({ message: '衣物不存在' });
    }

    res.json(clothes);
  } catch (error) {
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
};

// 添加衣物
export const addClothes = async (req, res) => {
  try {
    const {
      type, imageUrls,
      // 以下字段允许为空，用户可在后续编辑中补充
      name = '', color = '', season = [], occasions = [],
      purchaseDate, price = null, brand = '', material = '',
      size = '', isFavorite = false, lastWorn, description = '',
    } = req.body;

    const newClothes = new Clothes({
      name,
      type,
      color,
      season,
      occasions,
      purchaseDate,
      price,
      brand,
      material,
      size,
      isFavorite,
      lastWorn,
      imageUrls: imageUrls || [],
      description,
      userId: req.user._id,
    });

    await newClothes.save();

    res.status(201).json(newClothes);
  } catch (error) {
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
};

// 更新衣物
export const updateClothes = async (req, res) => {
  try {
    const { id } = req.params;
    const {
      name, type, color, season, occasions, purchaseDate,
      price, brand, material, size, isFavorite, lastWorn,
      imageUrls, description,
      sleeveLength = '', thickness = '', collarType = ''
    } = req.body;

    const userId = req.user._id;

    const updatedClothes = await Clothes.findOneAndUpdate(
      { _id: id, userId },
      {
        name,
        type,
        color,
        season,
        occasions,
        purchaseDate,
        price,
        brand,
        material,
        size,
        isFavorite,
        lastWorn,
        imageUrls,
        description,
        sleeveLength,
        thickness,
        collarType
      },
      { new: true, runValidators: true }
    );

    if (!updatedClothes) {
      return res.status(404).json({ message: '衣物不存在' });
    }

    res.json(updatedClothes);
  } catch (error) {
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
};

// 删除衣物
export const deleteClothes = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user._id;

    // 参数验证
    if (!id) {
      return res.status(400).json({ message: '衣物ID不能为空' });
    }

    // 验证ID格式
    if (!mongoose.Types.ObjectId.isValid(id)) {
      return res.status(400).json({ message: '无效的衣物ID' });
    }

    // 1. 首先查找所有包含该衣物的穿搭
    const deletedOutfits = await Outfit.find({ clothesIds: id });
    
    // 2. 删除所有包含该衣物的穿搭
    const deletedOutfitsCount = await Outfit.deleteMany({ clothesIds: id });

    // 3. 删除衣物本身
    const deletedClothes = await Clothes.findOneAndDelete({ _id: id, userId });

    if (!deletedClothes) {
      return res.status(404).json({ message: '衣物不存在' });
    }

    res.json({
      message: '删除成功',
      deletedClothes: deletedClothes.name,
      deletedOutfitsCount: deletedOutfitsCount.deletedCount,
      deletedOutfitsDetails: deletedOutfits.map(outfit => ({
        id: outfit._id,
        description: outfit.description
      }))
    });
  } catch (error) {
    console.error('删除衣物失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
};

// 批量删除衣物
export const deleteMultipleClothes = async (req, res) => {
  try {
    const { ids } = req.body;
    const userId = req.user._id;

    // 参数验证
    if (!Array.isArray(ids) || ids.length === 0) {
      return res.status(400).json({ message: '请提供有效的衣物ID数组' });
    }

    // 验证所有ID格式
    for (const id of ids) {
      if (!mongoose.Types.ObjectId.isValid(id)) {
        return res.status(400).json({ message: `无效的衣物ID: ${id}` });
      }
    }

    let totalDeletedOutfits = 0;
    const deletedClothesDetails = [];
    const deletedOutfitsDetails = [];

    // 1. 首先处理所有相关的穿搭数据
    for (const id of ids) {
      // 查找所有包含该衣物的穿搭
      const relatedOutfits = await Outfit.find({ clothesIds: id });
      
      // 删除所有包含这些衣物的穿搭
      const deleteResult = await Outfit.deleteMany({ clothesIds: id });
      totalDeletedOutfits += deleteResult.deletedCount;
      
      // 记录被删除的穿搭详情
      deletedOutfitsDetails.push(...relatedOutfits.map(outfit => ({
        id: outfit._id,
        description: outfit.description,
        clothesId: id
      })));
    }

    // 2. 批量删除衣物
    const clothesResult = await Clothes.find({ _id: { $in: ids }, userId });
    const deleteClothesResult = await Clothes.deleteMany({ _id: { $in: ids }, userId });
    
    // 记录被删除的衣物详情
    deletedClothesDetails.push(...clothesResult.map(clothes => ({
      id: clothes._id,
      name: clothes.name,
      type: clothes.type
    })));

    if (deleteClothesResult.deletedCount === 0) {
      return res.status(404).json({ message: '未找到要删除的衣物' });
    }

    res.json({
      message: '批量删除成功',
      deletedCount: deleteClothesResult.deletedCount,
      deletedClothes: deletedClothesDetails,
      deletedOutfitsCount: totalDeletedOutfits,
      deletedOutfits: deletedOutfitsDetails
    });
  } catch (error) {
    console.error('批量删除衣物失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
};

// 切换衣物收藏状态
export const toggleFavorite = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user._id;

    const clothes = await Clothes.findOne({ _id: id, userId });

    if (!clothes) {
      return res.status(404).json({ message: '衣物不存在' });
    }

    clothes.isFavorite = !clothes.isFavorite;
    await clothes.save();

    res.json(clothes);
  } catch (error) {
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
};

// 增加穿着次数
export const incrementWearCount = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user._id;

    const clothes = await Clothes.findOne({ _id: id, userId });

    if (!clothes) {
      return res.status(404).json({ message: '衣物不存在' });
    }

    clothes.wearCount = (clothes.wearCount || 0) + 1;
    clothes.lastWorn = new Date();
    await clothes.save();

    res.json(clothes);
  } catch (error) {
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
};

// 获取衣物分类统计
export const getCategoryStats = async (req, res) => {
  try {
    const userId = req.user._id;

    const stats = await Clothes.aggregate([
      { $match: { userId } },
      { $group: { _id: '$type', count: { $sum: 1 } } },
      { $sort: { count: -1 } }
    ]);

    // 转换格式为 { type: count }
    const result = {};
    stats.forEach(item => {
      result[item._id] = item.count;
    });

    res.json(result);
  } catch (error) {
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
};